import {
  LocationQueryRaw,
  NavigationGuardNext,
  RouteLocationNormalized,
  useRouter,
} from 'vue-router';
import { Message } from '@arco-design/web-vue';

import { useUserStore } from '@/store';

export default function useUser() {
  const router = useRouter();
  const userStore = useUserStore();
  const logout = async (logoutTo?: string) => {
    await userStore.logout();
    const currentRoute = router.currentRoute.value;
    Message.success('登出成功');
    await router.push({
      name: logoutTo && typeof logoutTo === 'string' ? logoutTo : 'SignIn',
      query: {
        ...router.currentRoute.value.query,
        redirect: currentRoute.name as string,
      },
    });
  };
  const jumpFirstPage = (
    to: RouteLocationNormalized,
    next: NavigationGuardNext
  ) => {
    if (to.name === 'SignIn') {
      next({
        name: 'PlatIdmOrgEmp',
        // name: 'PlatUserInfo',
        query: {
          redirect: to.name,
          ...to.query,
        } as LocationQueryRaw,
      });
      return;
    }
    next();
  };
  const jumpLoginPage = (
    to: RouteLocationNormalized,
    next: NavigationGuardNext
  ) => {
    if (to.name === 'SignIn') {
      next();
      return;
    }
    next({
      name: 'SignIn',
      query: {
        redirect: to.name,
        ...to.query,
      } as LocationQueryRaw,
    });
  };
  return {
    logout,
    jumpFirstPage,
    jumpLoginPage,
  };
}
